package com.subsequent.method;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.subsequent.dto.UserDto;
import com.subsequent.mapper.UsersMapper;
import com.subsequent.pojo.Users;
import com.subsequent.utils.BCrypt;
import com.subsequent.utils.Result;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;

@Component("passwordLoginStrategy")
public class PasswordLoginStrategy implements LoginStrategy{
    @Resource
    private UsersMapper usersMapper;
    @Override
    public Result login(UserDto dto) {
        //       参数验证
        if (dto == null) {
            return Result.error("手机号或密码或所属医院不能为空");
        }
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
//        比较手机号是否存在
        queryWrapper.lambda().eq(Users::getPhone, dto.getPhone());
        Users users = usersMapper.selectOne(queryWrapper);
//       判断用户是否为空
        if (users == null) {
            return Result.error("手机号不存在");
        }
        // 检查是否被锁定
        if (users.getLockedUntil() != null && users.getLockedUntil().after(new Date())) {
            return Result.error("账户已被锁定，请稍后再试");
        }
        // 验证密码
        if (!BCrypt.checkpw(dto.getPassword(), users.getPassword())) {
            int attempts = users.getLoginAttempts() + 1;
            if (attempts >= 3) {
                // 锁定账户，比如设定锁定时间为5分钟
                Calendar calendar = Calendar.getInstance();
                calendar.add(Calendar.MINUTE, 5); // 锁定5分钟后解锁
                users.setLockedUntil(calendar.getTime());
                users.setLoginAttempts(attempts);
                usersMapper.updateById(users);
                return Result.error("密码错误次数超过限制，账户已锁定，请5分钟后重试");
            } else {
                // 更新失败次数
                users.setLoginAttempts(attempts);
                usersMapper.updateById(users);
                return Result.error(201,"密码错误");
            }
        }
        // 登录成功，重置失败次数
        users.setLoginAttempts(0);
        users.setLockedUntil(null);
        usersMapper.updateById(users);
        return Result.success("登录成功", users);
    }
}
